package com.data.structure.algorithm.二分查找;

/**
 * @Description 二分查找，在一个数组中找一个数字，找到返回下标，找不到返回-1
 * @author ll
 * @createTime 2021/6/3  13:38 
 */
public class BinarySearch {

	/**
	 * 二分查找
	 * @param arr
	 * @param number
	 * @return 返回下标
	 */
	public static int binarySearch(int[] arr,int number){
		if(arr==null||arr.length==0){
			return -1;
		}
		//定义左中右下标
		int left = 0;
		int right = arr.length-1;
		int mid = 0;

		while(left<=right){
			//防止数据溢出
			mid = right-((right-left)>>1);
			if(arr[mid]<number){
				left = mid+1;
			}else if(arr[mid]>number){
				right = mid-1;
			}else{
				return mid;
			}
		}
		return mid;
	}

	public static void main(String[] args) {
		int arr[] = {1,2,3,4,5,6,7,8,9,10};
		System.out.println(binarySearch(arr, 8));
	}

}
